package top.riske.gen3d.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.UrlResource;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 文件下载工具类
 */
@Slf4j
public class FileDownloadUtils {

    private final RestTemplate restTemplate = new RestTemplate();

    public static void main(String[] args) throws IOException {
        String fileUrl = "https://ts1.tc.mm.bing.net/th/id/OVFT.f1zno4-zxcFQjpAhDJsXyi?w=154&h=77&c=7&rs=2&qlt=80&o=6&cb=thwsc5&dpr=1.3&pid=PopNow";
        String localFilePath = "D:/data.png";
        downloadFile(fileUrl, localFilePath);
    }

    /**
     * 从 URL 下载文件并保存到本地路径,文件后缀自动获取，默认为下载的文件的后缀
     * @param fileUrl  文件的完整 URL（如：https://example.com/files/data.pdf）
     * @param localPath 本地保存路径（如：/tmp/data.pdf）
     */
    public static void downloadFile(String fileUrl, String localPath) throws IOException {
        // 创建 URL 资源
        URL url = new URL(fileUrl);
        UrlResource resource = new UrlResource(url);

        // 确保父级目录存在
        File localFile = new File(localPath);
        File parentDir = localFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs(); // 创建所有必要的父级目录
        }

        // 获取输入流
        try (InputStream inputStream = resource.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(localPath)) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            log.info("文件下载成功！保存路径：{}", localPath);
        }
    }



}
